package reflect;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

/**
 * 自动调用被AutoRunClass标注的类中被@AutoRun标注的方法
 */
public class ReflectDemo8 {
    public static void main(String[] args) throws URISyntaxException, ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException {
        File dir = new File(
                ReflectDemo8.class.getResource(".").toURI()
        );
        File[] subs = dir.listFiles(f -> f.getName().endsWith(".class"));
        for (File sub : subs) {
            String fileName = sub.getName();
            String className = fileName.substring(0,
                    fileName.indexOf("."));

            Class cls = Class.forName("reflect." + className);
            //判断当前类对象表示的类是否被@AutoRunClass注解标注

            if (cls.isAnnotationPresent(AutoRunClass.class)) {
                System.out.println(className + "被标注了!");
                Object obj = cls.newInstance();

                //获取所有方法
                Method[] methods = cls.getDeclaredMethods();
                for (Method m : methods) {
                    //判断该方法是否被@AutoRun标注
                    if (m.isAnnotationPresent(AutoRun.class)) {
                        System.out.println(className + "的方法"
                                + m.getName() + "被标注了");
                        //通过该方法对象获取注解AutoRun
                        AutoRun ar = m.getAnnotation(AutoRun.class);
                        //通过AutoRun 获取标注时传入的参数value的值
                        int value = ar.value();
                        //根据value的值调用该方法对应次数
                        for (int i = 0; i < value; i++) {
                            m.invoke(obj);
                        }
                    }
                }
            }
        }
    }

}
